package cc.edge2.sns.services;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.jdo.PersistenceManager;
import javax.jdo.Query;

import net.arnx.jsonic.JSON;
import cc.edge2.sns.commons.PMF;
import cc.edge2.sns.models.SNSUser;

public class SearchUserService {
	public String execute(Map params, SNSUser user) {
		
		List<Map> userList = new ArrayList<Map>();
		PersistenceManager pm = PMF.get().getPersistenceManager();
		Query query = pm.newQuery(SNSUser.class);
		String name = (String)params.get("currentUserId");
		int a = -1;
		List<SNSUser> results = null;
		try {
			if(name != null && "".equals(name)) {
				query.setFilter("name >= :nameParam");
				query.setOrdering("name desc");
				query.setRange(0, 100);
				results = (List<SNSUser>)query.execute(name);
			} else {
				results = (List<SNSUser>)query.execute();
			}
			a = results.size();
			for(SNSUser tmpUser : results) {
				Map<String, String> userMap = new HashMap<String, String>();
				userMap.put("userId", "" + tmpUser.getUserId());
				userMap.put("name", tmpUser.getName());
				userMap.put("selfIntroduction", tmpUser.getSelfIntroduction());
				userMap.put("thumbnailUrl", tmpUser.getThumbnailUrl());
				userList.add(userMap);
			}
		} finally {
			query.closeAll();
		}
		
		Map<String, Object> result = new HashMap<String, Object>();
		Map<String, Object> contents = new HashMap<String, Object>();
		Map<String, Object> status = new HashMap<String, Object>();
		status.put("code", "0");
		status.put("message", "success");
		contents.put("searchResult", userList);
		contents.put("size", a);
		result.put("status", status);
		result.put("contents", contents);
		String value = JSON.encode(result);
		return value;
	}
}
